package org.tang.hool.webmvc;

import java.io.File;

/**
 * 根据模版名称匹配模版引擎
 *
 * @author Tang Jiujia
 * @since 2022/5/5
 */
public class ViewResolver {

    /**
     * 默认模版后缀
     */
    private final String DEFAULT_TEMPLATE_SUFFIX = ".html";

    /**
     * 存放模版页面的根目录
     */
    private File templateRootDir;

    /**
     * 模版名称
     */
    private String viewName;

    public ViewResolver(String templateRootPath) {
        ClassLoader classLoader = this.getClass().getClassLoader();
        String dirPath = classLoader.getResource(templateRootPath).getFile();
        this.templateRootDir = new File(dirPath);
    }

    /**
     * 根据视图名称解析视图引擎
     *
     * @param viewName 视图名
     * @return 视图引擎
     * @author Tang Jiujia
     * @since 2022/5/5
     */
    public View resolveViewName(String viewName) {
        this.viewName = viewName;
        if (viewName == null || "".equals(viewName.trim())) return null;
        viewName = viewName.endsWith(DEFAULT_TEMPLATE_SUFFIX) ?
                viewName : (viewName + DEFAULT_TEMPLATE_SUFFIX);
        String filePath = (templateRootDir.getPath() + "/" + viewName).replaceAll("/+", "/");
        File templateFile = new File(filePath);
        return new View(templateFile);
    }

    public String getViewName() {
        return viewName;
    }
}


